package cn.deepmax.anime.web.redis;

import cn.deepmax.anime.web.pojo.Section;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import java.awt.print.Pageable;
import java.io.Closeable;
import java.io.IOException;

@Slf4j
public class RedisTemplate implements Closeable {


    public static final String HOST = "localhost";
    public static final Integer PORT = 6379;
    public static final String AUTH = "wd1234567";
    private static JedisPool pool;


    static {
        JedisPoolConfig poolConfig = new JedisPoolConfig();
        poolConfig.setMaxTotal(50);// 最大连接数，连接全部用完，进行等待
        poolConfig.setMinIdle(10); // 最小空余数
        poolConfig.setMaxIdle(30); // 最大空余数
        if(AUTH==null){
            pool = new JedisPool(poolConfig, HOST, PORT);
        }else{
            pool = new JedisPool(poolConfig, HOST, PORT, 30000, AUTH);
        }
        log.info("Redis connect to {}:{} ", HOST, PORT);
    }



    public <E> E get(String key, Class<E> clazz){
        Jedis jedis = null;
        try{
            jedis = pool.getResource();
            String value = jedis.get(key);
            if(value==null){
                return null;
            }else{

                return JSON.parseObject(value, clazz);
            }
        }finally {
            if(jedis!=null){
                jedis.close();
            }
        }
    }

    public void set(String key, Object object){
        Jedis jedis = null;
        try{
            jedis = pool.getResource();
            if(object==null){
                jedis.del(key);
            }else{
                String value = JSON.toJSONString(object);
                jedis.set(key, value);
            }
        }finally {
            if(jedis!=null){
                jedis.close();
            }
        }
    }


    public void close() throws IOException {
        if(!pool.isClosed())
            pool.close();
    }



}
